<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="100px" size="mini">
      <el-form-item label="采购单号" prop="procureNo">
        <el-input v-model="queryParams.procureNo" clearable placeholder="请输入采购单号"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="queryParams.supplierName" clearable placeholder="请输入供应商名称"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="采购状态" prop="procureStatus">
        <el-select v-model="queryParams.procureStatus" clearable placeholder="请选择采购状态">
          <el-option v-for="dict in dict.type.erp_procure_batch" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="采购时间" prop="procureTime">
        <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期"
                        style="width: 240px" type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpProcure:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">新增采购单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpProcure:export']" icon="el-icon-download" plain size="mini" type="primary" @click="handleExport">列表导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpProcure:import']" icon="el-icon-upload2" plain size="mini" type="primary" @click="handleImport">批量导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  row-key="procureId" :data="ErpProcureList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" align="center" :reserve-selection="true" width="50" />
      <el-table-column align="center" label="采购单号" prop="procureNo" sortable width="200px;"/>
      <el-table-column align="center" label="供应商名称" prop="supplierName" width="300px;"/>
      <el-table-column align="center" label="采购状态" prop="procureStatus" sortable width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.procureStatus == 0" type="info">草稿</el-tag>
          <el-tag v-if="scope.row.procureStatus == 1" type="primary">待审批</el-tag>
          <el-tag v-if="scope.row.procureStatus == 2" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.procureStatus == 3" type="danger">被驳回</el-tag>
          <el-tag v-if="scope.row.procureStatus == 4" type="success">已完成</el-tag>
          <el-tooltip v-if="scope.row.procureStatus == 3" effect="light" placement="bottom">
            <div slot="content">
              {{ scope.row.rejectReason }}
            </div>
            <i class="el-icon-warning-outline" style="margin-left: 5px; color: red;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物流状态" prop="logisticsStauts" sortable width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_logistics_stauts" :value="scope.row.logisticsStauts"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="采购日期" prop="procureTime" sortable width="100px;">
        <template slot-scope="scope">
          <span>{{ scope.row.procureTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="采购人" prop="procurePersonName" width="100px;"/>
      <el-table-column align="center" label="联系电话" prop="procurePersonPhone" width="120px;"/>
      <el-table-column align="center" label="物流费用" prop="logisticsCost" width="100px;">
        <template slot-scope="scope">
          <span>{{ formattedNumber(scope.row.logisticsCost) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应付金额" prop="payAmount" width="100px;">
        <template slot-scope="scope">
          <span>{{ formattedNumber(scope.row.payAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审批人" prop="approveName" width="100px;"/>
      <el-table-column align="center" label="审批时间" prop="approveTime" width="160px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName" width="100px;"/>
      <el-table-column label="备注" prop="remark"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="220px;">
        <template slot-scope="scope">
          <el-button v-if="[0, 3].includes(scope.row.procureStatus)" v-hasPermi="['erp:ErpProcure:edit']" size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="[1].includes(scope.row.procureStatus)" v-hasPermi="['erp:ErpProcure:audit']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 2)">审核</el-button>
          <el-button v-if="[2].includes(scope.row.procureStatus)" v-hasPermi="['erp:ErpProcure:edit']" size="mini" type="text" @click="handleLogistics(scope.row)">更改物流状态</el-button>
          <el-button v-hasPermi="['erp:ErpProcure:view']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 1)">查看</el-button>
          <el-button v-if="[0, 1].includes(scope.row.procureStatus)" v-hasPermi="['erp:ErpProcure:edit']" size="mini" type="text" @click="handleUpdateFlag(scope.row)">关闭</el-button>
          <el-button v-if="[2, 4].includes(scope.row.procureStatus)" v-hasPermi="['erp:ErpProcure:print']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 3)">打印</el-button>
          <el-button v-if="[2, 4].includes(scope.row.procureStatus)" size="mini" type="text"
          @click="handleExportDetails(scope.row)" v-hasPermi="['erp:ErpProcure:export']">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination @current-change="handleCurrentChange" v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 审核or预览 -->
    <el-dialog :destroy-on-close="true" :title="viewAuditTitle" :visible.sync="viewOrAuditOpen" append-to-body width="80%">
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <div id="printCGForm" class="print_css">
          <div class="title">
            湖南胜博清洁服务有限公司（采购单）
          </div>
          <div class="head-print-5">
            <div>采购单号：{{ form.procureNo }}</div>
            <div>供应商：{{ form.supplierName }}</div>
            <div>采购日期：{{ parseTime(form.procureTime, "{y}年{m}月{d}日") }}</div>
            <div>采购人：{{ form.procurePersonName }}</div>
            <div>审核人：{{  form.approveName }}</div>
          </div>
          <right-toolbar :columns="columns" :refresh="false" :search="false" class="no-print"></right-toolbar>
          <table class="table_print">
            <tr>
              <th v-if="columns[0].visible" width="80px">序号</th>
              <th v-if="columns[1].visible">商品编号</th>
              <th v-if="columns[2].visible">商品名称</th>
              <th v-if="columns[3].visible">商品类别</th>
              <th v-if="columns[4].visible">单位</th>
              <th v-if="columns[5].visible">规格</th>
              <th v-if="columns[6].visible">采购单价</th>
              <th v-if="columns[7].visible">采购数量</th>
              <th v-if="columns[8].visible">小计</th>
            </tr>
            <tr v-for="(item,index) in form.detailsList" :key="index">
              <td v-if="columns[0].visible">{{index + 1}}</td>
              <td v-if="columns[1].visible">{{item.supplierCommodityNo}}</td>
              <td v-if="columns[2].visible">{{item.supplierCommodityName}}</td>
              <td v-if="columns[3].visible">{{item.supplierCommodityType}}</td>
              <td v-if="columns[4].visible">{{item.supplierCommodityUnit}}</td>
              <td v-if="columns[5].visible">{{item.supplierCommoditySpec}}</td>
              <td v-if="columns[6].visible">{{formattedNumber(item.procurePrice)}}</td>
              <td v-if="columns[7].visible">{{item.procureNumber}}</td>
              <td v-if="columns[8].visible">{{formattedNumber(item.procureNumber * item.procurePrice)}}</td>
            </tr>
          </table>
          <div class="head-print">
            <div>物流费用：{{ formattedNumber(form.logisticsCost) }} /
              {{ form.logisticsMethod == 1 ? '按重量' : '按体积' }}</div>
            <div>其他费用：{{ formattedNumber(form.otherCost) }} /
              {{ form.otherMethod == 1 ? '按重量' : '按体积' }}</div>
            <div>合计数量：{{ form.sumNumber }}</div>
            <div>合计金额：{{ formattedNumber(form.payAmount) }}</div>
          </div>
          <div class="single-line-print">制单人：{{ $store.getters.nickName}}</div>
          <div class="single-line-print">单据备注：{{ form.remark }}</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(2)">通过</el-button>
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(3)">驳回</el-button>
        <el-button v-if="type == 3" v-print="'#printCGForm'" type="primary">打印</el-button>
        <el-button @click="viewOrAuditOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="isUpdateLogisticsOpen" append-to-body title="更改物流状态" width="400px">
      <el-form :model="procureObj">
        <el-select v-model="procureObj.logisticsStauts" clearable placeholder="请选择" style="width: 90%;">
          <el-option v-for="dict in dict.type.erp_logistics_stauts" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isUpdateLogisticsOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateLogisticsSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 采购单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload ref="upload" :action="upload.url + '?updateSupport=' + upload.updateSupport" :auto-upload="false" :disabled="upload.isUploading"
                 :headers="upload.headers" :limit="1"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" accept=".xlsx, .xls" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的采购单数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addErpProcure,
  auditErpProcure,
  getErpProcure,
  listErpProcure,
  updateErpProcure,
  updateErpProcureUpdateLogistics
} from "@/api/erp/ErpProcure";
import {getToken} from "@/utils/auth";
import {formattedNumber} from "../../../utils/ruoyi";

export default {
  name: "ErpProcure",
  dicts: ['erp_procure_batch', 'erp_logistics_stauts'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      ErpProcureList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      viewAuditTitle: '',
      // 是否显示弹出层
      open: false,
      // 预览审核
      viewOrAuditOpen: false,
      form: {
        procurePerson: {},
        supplier: {}
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        procureNo: null,
        procureTime: null,
        procureStatus: null,
        supplierName: null,
      },
      // 选中采购单
      procureObj: {
        procureId: null,
        procureStatus: null,
      },
      // 更改物流状态
      isUpdateLogisticsOpen: false,
      // 打印列
      columns: [
        {key: 0, label: `序号`, visible: true},
        {key: 1, label: `商品编号`, visible: true},
        {key: 2, label: `商品名称`, visible: true},
        {key: 3, label: `商品类别`, visible: true},
        {key: 4, label: `单位`, visible: true},
        {key: 5, label: `规格`, visible: true},
        {key: 6, label: `采购单价`, visible: true},
        {key: 7, label: `采购数量`, visible: true},
        {key: 8, label: `小计`, visible: true},
      ],
      // 商品导入参数
      upload: {
        // 是否显示弹出层（商品导入）
        open: false,
        // 弹出层标题（商品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的商品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/erp/ErpProcure/importData"
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formattedNumber,
    /** 查询采购单列表 */
    getList() {
      this.loading = true;
      listErpProcure(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.ErpProcureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.procureId)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/ErpProcure/add-procure/erpProcure/0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push("/ErpProcure/add-procure/erpProcure/" + row.procureId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.procureId != null) {
            updateErpProcure(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addErpProcure(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 关闭 */
    handleUpdateFlag(row) {
      row.flag = 'N';
      this.$modal.confirm('是否确认关闭采购单编号为"' + row.procureNo + '"的数据项？').then(function () {
        return updateErpProcure(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    // 查看详情 / 审核
    handleViewOrAudit(row, type) {
      getErpProcure(row.procureId).then(res => {
        this.form = res.data;
        this.form.sumNumber = 0;
        this.form.detailsList.forEach(i => {
          this.form.sumNumber += i.procureNumber;
        })
        this.viewAuditTitle = '采购单：' + this.form.procureNo;
        this.type = type;
        this.viewOrAuditOpen = true;
      })
    },
    handleAuditOptions(type) {
      this.form.procureStatus = type;
      if (type == 3) {
        this.$prompt('', '驳回原因', {
          center: true,
          inputType: 'textarea',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          this.form.rejectReason = value;
          this.handleAudit();
        })
      } else {
        this.handleAudit();
      }
    },
    // 审核
    handleAudit() {
      auditErpProcure({
        procureId: this.form.procureId,
        procureStatus: this.form.procureStatus,
        rejectReason: this.form.rejectReason
      }).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.viewOrAuditOpen = false;
        this.getList();
      })
    },
    /** 更改物流状态 */
    handleLogistics(row) {
      this.procureObj = row;
      this.isUpdateLogisticsOpen = true;
    },
    /** 更改物流状态提交 */
    handleUpdateLogisticsSubmit() {
      updateErpProcureUpdateLogistics(this.procureObj).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.isUpdateLogisticsOpen = false;
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/ErpProcure/export', {
        ...this.queryParams,
        exportIds: this.ids?.join(',')
      }, `采购单_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "采购单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('erp/ErpProcure/importTemplate', {}, `采购单导入模版_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
     // 导出
     handleExportDetails(row){
      this.download('erp/ErpProcure/exportDetails/' + row.procureId, {}, `采购单_${row.procureNo}.xlsx`)
    }
  }
};
</script>
<style scoped>
.title {
  padding: 10px;
  text-align: center;
  font-size: 32px;
  font-weight: 500;
}

.oddInfo {
  font-size: 16px;
}

.remark {
  padding-top: 10px;
  padding-bottom: 10px;
}

/* 添加一个自定义类来覆盖默认的样式 */
.original-table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 20px;
}

.original-table td, .original-table th {
  border: 1px solid black;
  padding: 8px;
}


</style>
